package com.kancy.okhttp.client.log;

import com.kancy.okhttp.client.log.properties.OkHttpClientLogProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;

import java.util.List;

/**
 * HttpRequestLogRepositoryImpl
 *
 * @author kancy
 * @date 2020/5/2 11:47
 */
public class HttpRequestLogRepositoryImpl implements HttpRequestLogRepository {
    private static final Logger log = LoggerFactory.getLogger(HttpRequestLogRepositoryImpl.class);

    private final OkHttpClientLogProperties properties;
    private final List<HttpRequestLogRepository> repositories;

    public HttpRequestLogRepositoryImpl(OkHttpClientLogProperties properties, List<HttpRequestLogRepository> repositories) {
        this.properties = properties;
        this.repositories = repositories;
        // 排除自己
        repositories.remove(this);
        // 排序
        AnnotationAwareOrderComparator.sort(repositories);
        // 警告
        if (repositories.isEmpty()){
            log.warn("Not Found HttpRequestLogRepository.");
        }
    }


    /**
     * 保存第三方日志
     *
     * @param httpRequestLog
     */
    @Override
    public void save(HttpRequestLog httpRequestLog) {
        if (!properties.isEnabled() && repositories.isEmpty()){
            return;
        }
        repositories.stream().parallel().forEach(repository ->{
            try {
                repository.save(httpRequestLog);
            } catch (Exception e) {
                log.error("Unable to save HttpRequestLog in repository [{}] : {}", repository.getClass().getName(), e.getMessage());
            }
        });
    }
}
